package com.example.androidproject.movie.adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.androidproject.R;
import com.example.androidproject.base.ListAsGridBaseAdapter;
import com.example.androidproject.movie.bean.ResultBeanData;
import com.example.androidproject.movie.fragment.MovieFragment;

import java.util.ArrayList;

public class MovieAdapter extends ListAsGridBaseAdapter {
    private final Context mContext;
    private ArrayList<ResultBeanData.DataBean> data;

    public MovieAdapter(Context context, ArrayList<ResultBeanData.DataBean> data) {
        super(context);
        this.mContext = context;
        this.data = data;
    }

    @Override
    public int getItemCount() {
        return data.size();
    }


    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getItemView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if (view == null) {
            view = View.inflate(mContext, R.layout.movie_body_item, null);
            viewHolder = new ViewHolder();
            viewHolder.imageView = view.findViewById(R.id.iv_movie_body);
            viewHolder.textView = view.findViewById(R.id.tv_movie_body);
            viewHolder.linearLayout = view.findViewById(R.id.ll_movie_item);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        Glide.with(mContext).load(data.get(i).getSrc()).into(viewHolder.imageView);
        viewHolder.textView.setText(data.get(i).getName());
        viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                Message msg = new Message();
                bundle.putInt("position", i);
                msg.setData(bundle);
                MovieFragment.PostionHandler.sendMessage(msg);
            }
        });
        return view;
    }

    static class ViewHolder {
        ImageView imageView;
        TextView textView;
        LinearLayout linearLayout;
    }

    public void refresh(ArrayList<ResultBeanData.DataBean> data) {
        if (this.data == null) {
            this.data = new ArrayList<>();
        }
        this.data.addAll(data);
        this.notifyDataSetChanged();
    }
}
